package com.affectu.forum.action;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Factory;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.web.RequestParameter;

import com.affectu.dao.DAOBase;
import com.affectu.forum.Article;
import com.affectu.forum.Plate;

/**
 * Oct 7, 2008
 * 
 * @author daniel nathan
 */
@Name("forumPlateAction")
@Scope(ScopeType.EVENT)
public class PlateAction extends DAOBase {

	@RequestParameter()
	private Long plateId;

	public String addArticle(Article article) {
		try {
			article.setSender(this.getCurrentUser());
			article.setPlate(this.getPlateById());
			article.setSendDate(new Date());
			em.persist(article);
		} catch (Exception ex) {
			this.logException(ex);
		}
		return "/forum/plate.xhtml";
	}

	public Plate getPlateById() {
		Plate plate;
		try {
			if (this.plateId != null) {
				this.getSessionScope().put("plateId", this.plateId);
			} else {
				this.plateId = Long.valueOf(this.getSessionScope().get(
						"plateId").toString());
			}
			plate = (Plate) em.get(Plate.class, this.plateId);
		} catch (Exception ex) {
			plate = new Plate();
			this.logException(ex);
		}
		return plate;
	}

	@SuppressWarnings("unchecked")
	@Factory(value = "forumPlateAction_articles", scope = ScopeType.PAGE)
	public List<Article> getArticlesByPlateId() {
		List<Article> articles = new ArrayList<Article>();
		try {
			articles = em
					.createQuery(
							"from Article a where a.plate=:plate order by a.sendDate desc")
					.setParameter("plate", this.getPlateById()).list();
		} catch (Exception ex) {
			this.logException(ex);
		}
		return articles;
	}
}
